﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web.Http.Results;
using System.Web.Mvc; // needed for lambda includes
using System.Web;

using TheCup.ApiControllers;



namespace TheCup.Controllers
{

    public class MatchPlayController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Season(int Id)
        {
            ApiControllers.MatchPlayController c = new ApiControllers.MatchPlayController();

            ApiControllers.SeasonController s = new ApiControllers.SeasonController();
            ViewBag.Seasonlist = s.Get();

            Season thisseason = s.Get(Id);
            if (thisseason != null)
            {
                ViewBag.SeasonName = thisseason.Name;
            }

            ViewBag.SeasonId = Id; // we need this to render all matches for the selected season

            List<MatchPlayResult> results = c.GetSeason(Id).ToList<MatchPlayResult>();

            List<MatchPlayListEntry> l = new List<MatchPlayListEntry>();

            // find all players
            List<Player> p1s = (from p in results
                                              select p.Player1).Distinct().ToList<Player>();
            List<Player> p2s = (from p in results
                                              select p.Player2).Distinct().ToList<Player>();
            List<Player> players = p1s.Concat(p2s).GroupBy(x => x.Id).Select(x => x.First()).OrderBy(p => p.DisplayName).ToList<Player>();

            // loop through and calculate points and shit
            foreach (Player pl in players)
            {
                int matches = results.Where(r => (r.Player1Id == pl.Id) || (r.Player2Id == pl.Id)).Count();
                int won = results.Where(r => r.WinnerPlayerId == pl.Id).Count();
                int lost = results.Where(r => ((r.Player1Id == pl.Id) || (r.Player2Id == pl.Id)) && (r.WinnerPlayerId != null && r.WinnerPlayerId != pl.Id)).Count();
                int squared = results.Where(r => ((r.Player1Id == pl.Id) || (r.Player2Id == pl.Id)) && r.WinnerPlayerId == null).Count();

                MatchPlayListEntry entry = new MatchPlayListEntry();
                entry.MatchesPlayed = matches;
                entry.Player = pl;
                entry.MatchesLost = lost;
                entry.MatchesSquared = squared;
                entry.MatchesWon = won;
                l.Add(entry);
            }

            l = l.OrderByDescending(res => res.CalculatedPoints).ToList<MatchPlayListEntry>();

            int pos = 0;
            int prevval = 0;
            foreach (MatchPlayListEntry e in l)
            {
                if (e.CalculatedPoints != prevval)
                {
                    pos++;
                    prevval = e.CalculatedPoints;
                }
                e.Position = pos;
            }

            // get duplicate positions and mark with 'T'
            var dups = l.GroupBy(x => x.Position).Where(grp => grp.Count() > 1).Select(group => group);

            foreach (var d in dups)
            {
                l.Where(el => el.Position == d.Key).Select(tp => { tp.TiedPositionIndicator = "T"; return tp; }).ToList();
            }

            return View(l);
        }

        public ActionResult Details(int id)
        {
            ApiControllers.MatchPlayController bc = new ApiControllers.MatchPlayController();

            var actionResult = bc.GetSeason(id);
            var response = actionResult as OkNegotiatedContentResult<Blog>;
            if (response == null)
                return HttpNotFound();
            else
                return View(response.Content);
        }

        public class MatchResult
        {
            public int Value { get; set; }
            public string Name { get; set; }
        }

        [ChildActionOnly]
        public ActionResult AllMatchesForPlayer(int PlayerId)
        {
            ApiControllers.PlayerController bc = new ApiControllers.PlayerController();
            Player currentUser = bc.Get(User.Identity.Name);

            ApiControllers.MatchPlayController mpc = new ApiControllers.MatchPlayController();
            IEnumerable<MatchPlayResult> matches = mpc.GetAllMatchesForPlayer(currentUser.Id);

            return PartialView("_AllMatchesForPlayer", matches);
        }

        [ChildActionOnly]
        public ActionResult AllMatchesForSeason(int SeasonId)
        {
            ApiControllers.MatchPlayController mpc = new ApiControllers.MatchPlayController();
            IEnumerable<MatchPlayResult> matches = mpc.GetSeason(SeasonId);
            return PartialView("_AllMatchesForSeason", matches);
        }

        [Authorize]
        [HttpGet]
        public ActionResult Create()
        {
            MatchPlayResult e = new MatchPlayResult();
            e.Date = DateTime.Now.Date;

            ApiControllers.PlayerController bc = new ApiControllers.PlayerController();
            Player currentUser = bc.Get(User.Identity.Name);

            // setup viewbag for JQuery interaction
            ViewBag.CurrentUser = currentUser;
            ViewBag.CurrentPlayerId = currentUser.Id;
            ViewBag.CurrentPlayerDisplayName = currentUser.DisplayName;

            ApiControllers.MatchPlayController mpc = new ApiControllers.MatchPlayController();
            ViewBag.Players = mpc.GetPlayersNotPlayedForSeason(e.Date, currentUser.Id);

            List<MatchResult> results = new List<MatchResult>();
            results.Add(new MatchResult { Value = 0, Name = "A/S" });
            for (int n = 1; n < 11; n++)
            {
                results.Add(new MatchResult { Value = n, Name = n.ToString("0UP") });
            }
            ViewBag.PossibleResults = results;

            return View(e);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Create(MatchPlayResult e)
        {
            ApiControllers.PlayerController pc = new ApiControllers.PlayerController();
            Player currentUser = pc.Get(User.Identity.Name);
            e.Player1Id = currentUser.Id;

            string[] result = e.ResultString.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            int winnerid = int.Parse(result[0]);
            int holesup = int.Parse(result[1]);
            
            // if we have a winner, set that; if winnerid is 0 (zero), it is A/S (see JQuery code)
            if (winnerid != 0)
            {
                e.WinnerPlayerId = winnerid;
                e.HolesUp = holesup;
            }
            e.Player1Id = currentUser.Id;

            ApiControllers.MatchPlayController mpc = new ApiControllers.MatchPlayController();
            mpc.Post(e);

            return RedirectToAction("Create", "MatchPlay");
        }

        //[HttpDelete]
        [Authorize]
        public ActionResult Delete(int id)
        {
            using (var ctx = new TheCupContext())
            {
                var mp = ctx.MatchPlayResults.Where(x=>x.Id == id).First();
                ctx.MatchPlayResults.Remove(mp);
                ctx.SaveChanges();
            }

            return RedirectToAction("Create", "MatchPlay");
        }
    }
}
